/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

import {Config} from '@/Config.js'
import {Auth} from '@/utils/Auth.js'
import {Common} from '@/utils/Common.js'

export const Http = {
    config: {
        baseURL: Config.API_HOST,
        dataType: "json",
        data: {},
        showLoading: false,
        loadingText: "加载中...",
        showMessage: true
    },
    setParam(options) {
        //请求前处理，相当于请求拦截
        //如果config里有header字段，会自动在header里添加 Content-Type = "application/json"，所以header不加在config里
        let setting = Object.assign({}, this.config)
        setting = Object.assign(setting, options) //合并全局配置及局部配置项
        if (setting.url) {
            setting.url = setting.url.indexOf('http') === -1 ? setting.baseURL + setting.url : setting.url
        }
        setting.data = setting.data || {}
		
		// #ifdef H5
		let h5Type = Common.isWechat()?1:6;
		// #endif

        setting["header"] = {
            "authorization": Auth.getToken(),
			// #ifdef MP-WEIXIN
            "source": 2,
			// #endif
			// #ifdef APP-ANDROID
			"source": 4,
			// #endif
			// #ifdef APP-IOS
			"source": 3,
			// #endif
			// #ifdef H5
			"source": h5Type,
			// #endif
            "version": uni.getAppBaseInfo().appVersion
        }

        if (setting.showLoading) {
            uni.showLoading({
                "title": setting.loadingText,
                "mask": true
            });
        }

        return setting
    },
    returnData(setting, resolve, reject, res) {
        res = res[1]; //h5返回结果多出一个null,不知道为什么
        uni.stopPullDownRefresh()
        //结束loading提示
        if (setting.showLoading) {
            uni.hideLoading();
        }
        //请求成功，状态码200
        if (res.statusCode === 200) {
            if (Array.isArray(res.data)) {
                resolve(res.data)
                return
            }

            let data = (typeof res.data === "string") ? JSON.parse(res.data) : res.data;

            // if 与后台规定code代码进行处理数据返回
            if (data.code === 0) { //后台约定code=0为请求成功
                if (data.refreshToken) Auth.setToken(data.refreshToken)
                resolve(data.data)
            } else if (data.code === -2) { //后台约定code=-2为用户未登录
                Auth.removeToken()
                uni.showToast({
                    title: data.message,
                    icon: 'none'
                });
                //转入登录页
                setTimeout(function () {
                    Auth.toLogin()
                }, 1000);
            } else {
                if (setting.showMessage) {
                    if (!data.message) {
                        data.message = "服务器错误";
                        reject(data)
                        return;
                    }
                    if (data.message.length > 10) {
                        uni.showModal({
                            title: '提示',
                            content: data.message,
                            showCancel: false
                        })
                    } else {
                        uni.showToast({
                            title: data.message,
                            icon: 'none',
                            duration: 3000
                        })
                    }
                }
                reject(data.message)
            }
        } else {
            //状态码不是200
            uni.showToast({
                title: res.statusCode,
                icon: 'none'
            });
        }
    },

    /**
     * http请求
     * @param options
     * @returns {Promise<unknown>}
     */
    request(options) {
        let setting = this.setParam(options)
        setting.header['Content-Type'] = "application/json"

        return new Promise((resolve, reject) => {
            uni.request(setting).then(result => {
                this.returnData(setting, resolve, reject, result)
            });
        })
    },

    /**
     * 上传文件
     * @param options
     * @returns {Promise<unknown>}
     */
    uploadFile(options) {
        let setting = this.setParam(options)
        setting.url = setting.baseURL + "/file/upload"
        setting.formData = setting.data
        setting.name = "file"

        uni.showLoading({
            title: '上传中...'
        });

        return new Promise((resolve, reject) => {
            uni.uploadFile(setting).then(result => {
                uni.hideLoading();
                this.returnData(setting, resolve, reject, result)
            });
        })
    },

    dateToTimestamp(timestamp) {
        if (!timestamp) return timestamp;
        if (timestamp === 0) return 0;
        return Date.parse(new Date(timestamp).toString())
    },

    timestampToDate(timestamp) {
        if (!timestamp) return "";
        timestamp = timestamp ? timestamp : null;
        let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
        let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
        let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
        let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        return Y + M + D + h + m + s;
    }
}
